/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import "CleanUpView.h"

#import "spds/constants.h"
#import "customs.h"
#import "FunambolAPI.h"


@implementation CleanUpView

- (id) init {
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"Clean Up",@"Clean Up");
	}
	return self;
}    

- (void) dealloc {
    // TODO: destruct
    
    [super dealloc];
}

- (void) loadView{
    
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
	
	self.view.autoresizesSubviews = YES;

    small_font = [UIFont systemFontOfSize:15];
    

    cleanupTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    cleanupTable.delegate = self;
    cleanupTable.dataSource = self;
	//cleanupTable.rowHeight = 40;
    [cleanupTable setAutoresizesSubviews:YES];
    [cleanupTable setAutoresizingMask:UIViewAutoresizingFlexibleHeight + UIViewAutoresizingFlexibleBottomMargin];
    
    [self.view addSubview:cleanupTable]; 
    
    contactSyncCell   = [[UITableViewCell alloc]init];
    calendarSyncCell  = [[UITableViewCell alloc]init];
    noteSyncCell      = [[UITableViewCell alloc]init];

    descriptionCell   = [[UITableViewCell alloc]init];
    descriptionCell.selectionStyle = UITableViewCellSelectionStyleNone; 

    UITextView * description= [[UITextView alloc] initWithFrame: CGRectMake(20, 10, descriptionCell.contentView.bounds.size.width-40, 110)];
#ifdef FUNAMBOL_APP_STORE
        description.text = NSLocalizedString(@"Clean up Text", @"Clean up Text");
#else
        description.text = NSLocalizedString(@"Clean up Text 1", @"Clean up Text 1");
#endif
    [description setEditable:NO];
    [description setFont:small_font];
    [description setScrollEnabled:NO];
    [description setAutoresizesSubviews:YES];
    
    [descriptionCell addSubview:description];


    [[contactSyncCell textLabel] setText:NSLocalizedString(@"Contacts", @"Contacts...")];
    [[calendarSyncCell textLabel] setText:NSLocalizedString(@"Calendar", @"Calendar...")];
    [[noteSyncCell textLabel] setText:NSLocalizedString(@"Notes", @"Notes...")];
	
    contactSync       =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [contactSync addTarget:self action:@selector(contactSyncAction:) forControlEvents:UIControlEventValueChanged];
    [contactSync setOn:NO animated:NO];
    
    calendarSync      =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [calendarSync addTarget:self action:@selector(calendarSyncAction:) forControlEvents:UIControlEventValueChanged];
    [calendarSync setOn:NO animated:NO];
    
    noteSync          =   [[UISwitch alloc] initWithFrame:CGRectMake(200.0, 10.0, 60.0, 30)];
    [noteSync addTarget:self action:@selector(noteSyncAction:) forControlEvents:UIControlEventValueChanged];
    [noteSync setOn:NO animated:NO];

    [contactSyncCell addSubview:contactSync];
    [calendarSyncCell addSubview:calendarSync];
    [noteSyncCell addSubview:noteSync];
        
#ifdef FUNAMBOL_APP_STORE
        cleanupButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Yes",@"Yes...")
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(cleanupAction:)];    
#else
        cleanupButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Start",@"Start...")
                                                         style:UIBarButtonItemStylePlain
                                                        target:self
                                                        action:@selector(cleanupAction:)];
#endif

    self.navigationItem.rightBarButtonItem = cleanupButton;
    [cleanupButton setEnabled:YES];   
    
    [cleanupTable reloadData];
}

- (void) reload
{
}

- (void) viewDidAppear:(BOOL)animated{
    [self contactSyncAction:nil];
}



- (void) contactSyncAction: (id)sender
{
    if ([contactSync isOn])
    {
        contactFlag = true;
    }
    else
    {
        contactFlag = false;
    }
}

- (void) calendarSyncAction: (id)sender
{
    if ([calendarSync isOn])
    {
        calendarFlag = true;
    }
    else
    {
        calendarFlag = false;
    }
}

- (void) noteSyncAction: (id)sender
{
    if ([noteSync isOn])
    {
        noteFlag = true;
    }
    else
    {
       noteFlag = false;
    }
}

- (void) cleanupAction: (id)sender
{
#ifndef FUNAMBOL_APP_STORE
	if (noteFlag || calendarFlag || contactFlag)
    {
        bool calendarNotSynced = false;
        bool noteNotSynced = false;
#endif

        bool contactNotSynced = false;

        int sourcesnotsynced = 0;
        
        if(([[FunambolAPI getInstance]getSyncSourceLastSyncDate:@"addressbook"] == 0) && 
           !([[[FunambolAPI getInstance]getSync:@"addressbook"]isEqualToString:@"none"])){
            contactNotSynced = true;
            sourcesnotsynced++;
        }
#ifndef FUNAMBOL_APP_STORE
        
            if([[FunambolAPI getInstance]getSyncSourceLastSyncDate:@"calendar"] == 0 &&
               !([[[FunambolAPI getInstance]getSync:@"calendar"]isEqualToString:@"none"])){
                calendarNotSynced = true;
                sourcesnotsynced++;
            }
            if([[FunambolAPI getInstance]getSyncSourceLastSyncDate:@"note"] == 0 &&
               !([[[FunambolAPI getInstance]getSync:@"calendar"]isEqualToString:@"none"])){
                noteNotSynced = true;
                sourcesnotsynced++;
            }
		
#endif        
		if(sourcesnotsynced > 0){
            alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", @"Alert")
                                                message:NSLocalizedString(@"Want to cleanup notsynced sources",@"Want to cleanup notsynced sources")
                                                delegate:self 
                                                cancelButtonTitle:NSLocalizedString(@"OK",@"OK") 
                                                otherButtonTitles:NSLocalizedString(@"Cancel",@"Cancel"), nil];
            [alert setTag:2];
			[alert show];
            [alert release];

        }else{
            clickedCleanup = true;
            [[self navigationController] popViewControllerAnimated:YES];
        }
    
#ifndef FUNAMBOL_APP_STORE
    } else {
        clickedCleanup = false;
    }
#endif
}

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == 0){//OK
		clickedCleanup = true;
		[[self navigationController] popViewControllerAnimated:YES];
	}else{//Cancel
		clickedCleanup = false;
		[[self navigationController] popViewControllerAnimated:YES];
	}
}
                              
                              
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            return 130;
        default:
            return 40;
        break;
    }
    cleanupTable.rowHeight;
}

- (UITableViewCell *)tableView:(UITableView *)contactsTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    return descriptionCell;
                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    return contactSyncCell;
                case 1:
                    return calendarSyncCell;
                case 2:
                    return noteSyncCell;
                default:
                    break;
            }
            break;
        default:

            break;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)contactsTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            // Cannot select description
            [cleanupTable deselectRowAtIndexPath:indexPath animated:YES];
            return;
            break;
        //case 1:
        //    break;
        default:
            break;
    }

}

- (NSInteger)tableView:(UITableView *)contactsTable numberOfRowsInSection:(NSInteger)section {
        switch (section) {
            case 0:
                return 1;
            case 1:
                return 3; //3                    
            default:
                break;
        }
    return 0;//should never happen
}



- (void)viewWillAppear:(BOOL)animated
{
    clickedCleanup = false;

	// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
	NSIndexPath *indexPath = [cleanupTable indexPathForSelectedRow];
    if(!indexPath)
        return;
        
	[cleanupTable deselectRowAtIndexPath:indexPath animated:NO];
    
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)contactsTable {
    
#ifndef FUNAMBOL_APP_STORE
        return 2;
#else
        return 1;
#endif
}

- (bool) didClickCleanup
{
    return clickedCleanup;
}

- (bool) getContactFlag{
    return contactFlag;
}
- (bool) getCalendarFlag{
    return calendarFlag;
}
- (bool) getNoteFlag{
    return noteFlag;
}
@end
